<script setup lang="ts">
import fileTree from '@/components/file-tree/index.vue'
import {ref} from "vue";
import SvgIcon from "@/components/svg-icon/index.vue";
import {useRoute, useRouter} from "vue-router";
import {useCommonStore} from "@/stores/common";
import {shareList, createdShareLink, checkPassword} from "@/api/share";
import {ElMessage} from "element-plus";
import Preview from "@/components/preview/index.vue";
import {getFileRemainingDays} from "@/utils/textUtils";
import {useUserInfoStore} from "@/stores/user_info";
import loading from "@/components/loading/index.vue"
import {getBaseUrl} from "@/utils/env";

let fileInfo = ref({})
const list = ref([])
let showLoading = ref(true)

const route = useRoute()
const router = useRouter()
const commonStore = useCommonStore()
const userStore = useUserInfoStore()
const shareId = route.params.id.split('.')[0]
const token = commonStore.shareFileToken[shareId]
//选中文件列表
const checkItemList: any = ref([])

const getShareList = async () => {
  await shareList(token, shareId).then((res: any) => {
    list.value = res.data.list
    fileInfo.value = res.data
    showLoading.value = false
  }).catch((res: any) => {
    router.push('/verify/' + (route.params.id.includes('.html') ? route.params.id : route.params.id + ".html"))
  })
}


if (token) {
  getShareList()
} else {
  checkPassword({
    shareId: shareId
  }).then((res: any) => {
    commonStore.shareFileToken[shareId] = res.data
    getShareList()
  }).catch(((res) => {
    router.push('/verify/' + (route.params.id.includes('.html') ? route.params.id : route.params.id + ".html"))
  }))
}


const downFiles = () => {

}

// 文件面包屑
const breadcrumb: any = ref([])

const breadcrumbBox = ref<any>({})


//全选/反选
const checkAll = ref(false)
const handleCheckAllChange = (val: boolean) => {
  checkAll.value = val
  list.value.forEach((item: any) => {
    item.ischeck = val
    let index = checkItemList.value.findIndex((i: any) => i.id == item.id)

    if (val && index == -1) {
      checkItemList.value.push(item)
    }
  })

  if (!val) {
    checkItemList.value.length = 0
  }
}
const type = ref<any>('')
const id = ref<any>('')
const dialog = ref()
let topId = 0
const changeFileTree = async (item: any) => {

  // 如果是文件在进入文件
  if (item.type == "folder") {
    breadcrumb.value.push(item)
    folderIndex.value = item.id
    if (item.parentId == 0) {
      topId = item.id
    }
    showLoading.value = true
    await shareList(token, shareId, item.id, topId).then((res: any) => {
      list.value = res.data.list
      fileInfo.value = res.data
      showLoading.value = false
    }).catch((res: any) => {
      console.log(res)
      router.push('/verify/' + route.params.id)
    })
  } else {
    // 未登录不支持预览
    if (!userStore.token) {
      ElMessage({
        message: '登录后支持预览',
        type: 'error',
        plain: true,
      })
      return;
    }
    // 文件状态不对不支持预览，直接返回
    if (item.status != 0) {
      ElMessage({
        message: '该状态不支持预览',
        type: 'error',
        plain: true,
      })
      return
    }
    // 如果是图片在预览
    commonStore.isPreview = true
    type.value = item.type
    id.value = item.id
  }
}
let folderIndex = ref(-1)
const toPath = async (id: any, index?: any) => {
  // 如果是当前选中就直接返回
  if (folderIndex.value == id) {
    return;
  }
  // 如果是根元素就清除面包屑
  if (id == -1) {
    breadcrumb.value.length = 0
    await shareList(token, shareId).then((res: any) => {
      list.value = res.data.list
      fileInfo.value = res.data
      showLoading.value = false
    }).catch((res: any) => {
      router.push('/verify/' + route.params.id)
    })
    return
  }
  // 查询元素下标
  let currentItem = breadcrumb.value.find((item: any) => {
    return item.id == id
  })
  breadcrumb.value.splice(index + 1, breadcrumb.value.length - index)
  await shareList(token, shareId, currentItem.id, topId).then((res: any) => {
    list.value = res.data.list
    fileInfo.value = res.data
    showLoading.value = false
  }).catch((res: any) => {
    router.push('/verify/' + route.params.id)
  })
}

const download = async (item: any) => {
  checkItemList.value.push(item)
  startDownFiles()
}

const startDownFiles = () => {
  const list = checkItemList.value.map((item: any) => item.id)
  createdShareLink({
    token,
    fileId: list.join(",")
  }).then((res: any) => {
    let link = document.createElement("a");
    link.download = decodeURIComponent(checkItemList.value[0].name);
    link.style.display = "none";
    const serviceUrl = getBaseUrl()
    link.href = serviceUrl + "/file/download?token=" + res.data;
    link.click();
    link.remove();
    handleCheckAllChange(false)

    // 提示开始下载
    ElMessage({
      message: '创建下载成功',
      type: 'success',
      plain: true,
    })

  }).catch(() => {
    ElMessage({
      message: '创建下载失败',
      type: 'error',
      plain: true,
    })
  }).finally(() => {
    handleCheckAllChange(false)
    checkItemList.value.length = 0
  })
}
const checkItem = (val: any) => {
  let index = checkItemList.value.findIndex((item: any) => item.id == val.id)
  if (index != -1) {
    checkItemList.value.splice(index, 1)
  } else {
    checkItemList.value.push(val)
  }
  checkAll.value = list.value.every((item: any) => item.ischeck);
}

</script>

<template>
  <div class="share-list">
    <teleport to="body">
      <div v-if="commonStore.isPreview" class="preview">
        <Preview :type="type" :id="id"></Preview>
      </div>
    </teleport>
    <div class="header">

      <div class="left">
        <h4 class="name">{{ fileInfo.nickName }}</h4>
        <p>{{ getFileRemainingDays(fileInfo.savingTime) }}内有效</p>
      </div>

      <div>
        <el-button v-if="checkItemList.length>0" @click="startDownFiles" size="large" color="#597DFC"
                   style="color: #fff">浏览器下载
        </el-button>
      </div>
    </div>
    <div class="content">
      <div class="breadcrumb">
        <div style="cursor: pointer;min-width: 60px" @click="toPath(-1)">
          我的文件
        </div>
        <div>
          <el-breadcrumb style="width: 100%;display: flex;align-items: center" separator="/">
            <div v-if="breadcrumb.length > 0">&nbsp;&nbsp;->&nbsp;&nbsp;</div>
            <div class="breadcrumb-box">
              <el-breadcrumb-item v-for="(item,index) in breadcrumb" @click="toPath(item.id,index)" :key="index">
                <div style="display: flex;cursor: pointer">
                  <div class="breadcrumb-item">{{ item.name }}</div>
                </div>
              </el-breadcrumb-item>
            </div>
          </el-breadcrumb>
        </div>
      </div>
      <div v-if="showLoading" class="loading">
        <loading></loading>
      </div>

      <div v-show="!showLoading">
        <file-tree @onclick="changeFileTree" @check="checkItem" :list="list">
          <template #header>
            <table style="table-layout: fixed;width: 100%;height: 40px;border-bottom: 1px solid #ccc;">
              <colgroup class="tab_column">
                <col width="5%">
                <col width="45%">
                <col width="10%">
                <col width="20%">
                <col width="20%">
              </colgroup>
              <thead>
              <tr>
                <th>
                  <el-checkbox
                      v-model="checkAll"
                      @change="handleCheckAllChange"></el-checkbox>

                </th>
                <th>
                  <div style="text-align: left;margin-left: 15px">
                    文件
                  </div>
                </th>
                <th>
                </th>
                <th>
                  创建时间
                </th>
                <th>
                  大小
                </th>
              </tr>
              </thead>
            </table>
          </template>
          <template v-slot="menu">
            <div style='display: flex;gap: 20px;justify-content: center'>
              <!--              <el-tooltip-->
              <!--                  v-if="userStore.token"-->
              <!--                  effect="dark"-->
              <!--                  content="保存"-->
              <!--                  :hide-after="0"-->
              <!--                  placement="top"-->
              <!--                  :show-after="100"-->
              <!--              >-->
              <!--                <div style="background-color: #FAFAFA">-->
              <!--                  <svg-icon style="width: 20px;height: 20px" name="unloading"/>-->
              <!--                </div>-->

              <!--              </el-tooltip>-->
              <el-tooltip
                  content="下载"
                  :hide-after="0"
                  :show-after="100"
                  placement="top"
              >
                <div @click="download(menu.menu)" style="background-color: #FAFAFA">
                  <svg-icon style="width: 20px;height: 20px;" name="down"/>
                </div>

              </el-tooltip>
            </div>
          </template>
        </file-tree>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.share-list {
  width: 1300px;
  margin: 0 auto;

  .header {
    margin-top: 30px;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .left {
      display: flex;
      flex-direction: column;
      gap: 10px;

      p {
        font-size: 12px;
        color: #999;
      }
    }

    .name {
      max-width: 150px;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
  }

  .content {
    margin-top: 40px;

    .breadcrumb {
      max-width: 1300px;
      width: 100%;
      height: 40px;
      border-radius: 15px;
      top: 0;
      display: flex;
      align-items: center;
      padding: 0 10px;
      box-sizing: border-box;

      .breadcrumb-item {
        max-width: 110px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        padding: 10px 0;
      }

      .breadcrumb-box {
        max-width: 1100px;
        display: flex;
        flex-wrap: nowrap;
        justify-content: flex-end;
        overflow: hidden
      }
    }
  }
}

.preview {
  position: fixed;
  width: 100vw;
  height: 100vh;
  top: 0;
  left: 0;
  z-index: 100;
}

</style>